<!-- 海量点地图 -->
<!-- 
    各个城市的信息（坐标等）: https://webapi.amap.com/ui/1.1/ui/geo/DistrictExplorer/assets/d_v1/country_tree.json
    所有地图相关的实例不要放在 vue 的可响应数据中，响应数据会劫持属性，地图的属性会被修改，另外，劫持的属性可能和渲染有关，那么会增加很多响应的计算，会很卡;
    组件ref的方法 addPoint(mapData), // 添加点位的数组
    组件ref的方法 initMap('石家庄'), // 初始化地图 默认不传为石家庄
-->
<template>
  <div
    v-loading="loading"
    element-loading-text="数据量较大，正在为您加载......"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    id="magnanimity"
    ref="magnanimity"
    style="width: 100%; height: 100%"
  ></div>
</template>

<script setup>
import { ref, shallowRef } from "vue";
import { bestFn } from "./initSelect";
import img from "./img/point.png";
import axios from "axios";

const magnanimity = shallowRef(null); //地图dom
// 接收传过来的参数
const props = defineProps({
  data: Array, //传过来的点位数据
});
let mapData = props.data; // 传过来的点位数据
let mapp = null; // new AMap.Map备份
let massMarksObj = null; //massMarks备份
let loading = ref(false);

// 父组件添加点位方法
const addPoint = (data = []) => {
  if (data.length == 0) {
    alert("请传入要添加点位的数组");
    return;
  }
  mapData = data;
  addPonits(AMap, mapp);
};

// 处理加载地图的放大等级
const Level = (val) => {
  console.log(val);
  let level = 0;
  switch (val.level) {
    case "province":
      level = 6;
      break;
    case "city":
      level = 9;
      break;
    case "district":
      level = 12;
      break;
  }
  return level;
};

// 初始化地图
const initMap = async (area = "石家庄") => {
  area = area.trim().length == 0 ? "石家庄市" : area.trim();
  let city = [];
  // 添加city接口 "缓存"
  if (!sessionStorage.getItem("mapCity")) {
    city = await axios.get(
      "https://webapi.amap.com/ui/1.1/ui/geo/DistrictExplorer/assets/d_v1/country_tree.json"
    );
    city = [city.data];
    sessionStorage.setItem("mapCity", JSON.stringify(city));
  } else {
    city = JSON.parse(sessionStorage.getItem("mapCity"));
  }
  if (!bestFn(city, area)) {
    alert("您搜索的地区不存在");
    return;
  }
  let findCity = bestFn(city, area);
  console.log(findCity.center);
  let map = new AMap.Map("magnanimity", {
    zoom: Level(findCity), //级别
    //设置地图容器id
    pitch: 40, // 倾斜度
    viewMode: "3D", //是否为3D地图模式
    center: findCity.center, //中心点坐标
    layers: [
      new AMap.TileLayer.Satellite(), // 卫星图
    ],
  });
  mapp = map;
  // 添加遮罩
  addMask(AMap, map, area);
  // 添加海量标记点
  addPonits(AMap, map);
};

// 遮罩
const addMask = (AMap, map, area) => {
  AMap.plugin("AMap.DistrictSearch", function () {
    var districtSearch = new AMap.DistrictSearch({
      level: "province", // 关键字对应的行政区级别，country表示国家
      subdistrict: 1, // 显示下级行政区级数，1表示返回下一级行政区
      extensions: "all", //返回行政区边界坐标组等具体信息
    });
    // 搜索所有省/直辖市信息
    districtSearch.search(area, function (status, result) {
      //添加描边
      var bounds = result.districtList[0].boundaries;
      // 遮罩 👇
      var outer = [
        new AMap.LngLat(-360, 90, true),
        new AMap.LngLat(-360, -90, true),
        new AMap.LngLat(360, -90, true),
        new AMap.LngLat(360, 90, true),
      ];
      var pathArray = [outer];
      pathArray.push.apply(pathArray, bounds);
      // 遮罩 👆
      if (bounds) {
        for (var i = 0, l = bounds.length; i < l; i++) {
          var polygon = new AMap.Polygon({
            map: map,
            strokeWeight: 1, // 边界宽度
            strokeColor: "#34e3e1", // 边界颜色
            fillColor: "black", // 这找颜色
            fillOpacity: 0.7, // 遮罩透明度
            path: bounds[i],
          });
        }
        polygon.setPath(pathArray);
        map.add(polygon);
      }
    });
  });
};

// 海量标记点
const addPonits = (AMap, map) => {
  console.log("当前标记的数据量为: ", mapData);
  loading.value = true;
  var styleObject = {
    url: img, // 图标地址
    size: new AMap.Size(21, 31), // 图标大小
    anchor: new AMap.Pixel(11, 16), // 图标显示位置偏移量，基准点为图标左上角
  };
  massMarks?.clear();
  var massMarks = new AMap.MassMarks(mapData, {
    alwaysRender: false,
    zIndex: 111,
    zooms: [3, 19],
    cursor: "pointer",
    style: styleObject, // 设置样式对象
  });
  massMarksObj = massMarks; // 备份massMarks
  makerClick(); // 标记点点击事件--->打开弹窗
  massMarks.setMap(map);
  massMarks.on("complete", (e) => {
    loading.value = false;
    console.log(e, "海量点添加完毕");
  });
};

// 标记点点击事件
const makerClick = () => {
  new AMap.Marker({ content: " ", map: mapp });
  massMarksObj.on("click", function (e) {
    openWindow(e.data);
  });
};

// 真正的打开弹窗
const openWindow = (data) => {
  // 信息窗体的内容
  var content = `
    <div class="map-inner-wrap">
      <h1>区域名称: ${data.name} </h1>
      <h1>经度: ${data.lnglat[0]}, 纬度:${data.lnglat[1]} </h1>  
    </div>
  `;
  // 创建 infoWindow 实例
  var infoWindow = new AMap.InfoWindow({
    anchor: "bottom-center", //窗体出现位置
    content: content, //传入 dom 对象，或者 html 字符串
  });

  // 打开信息窗体
  infoWindow.open(mapp, data.lnglat);
};

// 暴露方法
defineExpose({
  addPoint, // 添加点位
  initMap, // 初始化地图
});
</script>

<style lang="scss">
/*去掉高德地图logo*/
// .amap-logo {
//   display: none !important;
// }
// .amap-copyright {
//   opacity: 0;
// }
// .amap-labels {
//   opacity: 0.6;
// }
// .amap-info-content {
//   width: 600px;
//   box-shadow: 0 0 10px 3px #61c7e6 !important;
//   background: rgba(18, 75, 109, 0.8);
//   border-radius: 5px;
//   color: #fff;
//   font-size: 12px;
//   padding: 10px;
//   border: none;
//   .map-inner-wrap {
//     padding: 10px;
//   }
//   .amap-info-close {
//     color: #fff;
//   }
// }
// .amap-info-sharp {
//   border-top-color: rgba(18, 75, 109, 0.8) !important;
// }
</style>
